class ScrcpyClient {
    constructor() {
        this.socket = null;
        this.currentDevice = null;
        this.isStreaming = false;
        this.mediaSource = null;
        this.sourceBuffer = null;
        this.videoQueue = [];
        this.isProcessing = false;
        
        this.init();
    }

    init() {
        this.setupSocket();
        this.setupEventListeners();
        this.checkServerStatus();
        this.loadDevices();
    }

    setupSocket() {
        this.socket = io();
        
        this.socket.on('connect', () => {
            console.log('已连接到服务器');
            this.updateStatus('server', 'connected');
        });

        this.socket.on('disconnect', () => {
            console.log('与服务器断开连接');
            this.updateStatus('server', 'disconnected');
        });

        this.socket.on('connect_error', (error) => {
            console.error('连接错误:', error);
            this.updateStatus('server', 'error');
            this.showNotification('服务器连接失败', 'error');
        });
    }

    setupEventListeners() {
        // 刷新设备按钮
        document.getElementById('refreshDevices').addEventListener('click', () => {
            this.loadDevices();
        });

        // 检查状态按钮
        document.getElementById('checkStatus').addEventListener('click', () => {
            this.checkServerStatus();
        });

        // 返回设备列表按钮
        document.getElementById('backToDevices').addEventListener('click', () => {
            this.showDeviceList();
        });

        // 停止投屏按钮
        document.getElementById('stopStream').addEventListener('click', () => {
            this.stopStreaming();
        });

        // 截图按钮
        document.getElementById('takeScreenshot').addEventListener('click', () => {
            this.takeScreenshot();
        });

        // 设备信息切换
        document.getElementById('toggleDeviceInfo').addEventListener('click', () => {
            this.toggleDeviceInfo();
        });

        // 文本发送
        document.getElementById('sendText').addEventListener('click', () => {
            this.sendText();
        });

        // 回车键发送文本
        document.getElementById('textInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendText();
            }
        });

        // 控制按钮事件委托
        document.addEventListener('click', (e) => {
            if (e.target.closest('.control-btn')) {
                const button = e.target.closest('.control-btn');
                const action = button.dataset.action;
                this.handleControlAction(action);
            }
        });

        // 视频播放器触摸事件
        this.setupVideoTouchEvents();
    }

    setupVideoTouchEvents() {
        const videoPlayer = document.getElementById('videoPlayer');
        const videoOverlay = document.getElementById('videoOverlay');
        
        // 点击视频覆盖层开始投屏
        videoOverlay.addEventListener('click', () => {
            if (this.currentDevice && !this.isStreaming) {
                this.startStreaming();
            }
        });

        // 触摸事件处理
        let touchStartTime = 0;
        let touchStartX = 0;
        let touchStartY = 0;
        let isLongPress = false;
        let longPressTimer = null;

        videoPlayer.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            touchStartTime = Date.now();
            touchStartX = touch.clientX;
            touchStartY = touch.clientY;
            isLongPress = false;

            // 长按检测
            longPressTimer = setTimeout(() => {
                isLongPress = true;
                this.sendTouchEvent('longpress', touchStartX, touchStartY);
            }, 500);
        });

        videoPlayer.addEventListener('touchend', (e) => {
            e.preventDefault();
            if (longPressTimer) {
                clearTimeout(longPressTimer);
            }

            if (!isLongPress) {
                const touch = e.changedTouches[0];
                const touchEndTime = Date.now();
                const duration = touchEndTime - touchStartTime;

                if (duration < 200) {
                    // 短按
                    this.sendTouchEvent('tap', touch.clientX, touch.clientY);
                } else {
                    // 滑动
                    const deltaX = touch.clientX - touchStartX;
                    const deltaY = touch.clientY - touchStartY;
                    
                    if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
                        this.sendTouchEvent('swipe', {
                            startX: touchStartX,
                            startY: touchStartY,
                            endX: touch.clientX,
                            endY: touch.clientY
                        }, duration);
                    }
                }
            }
        });

        // 鼠标事件处理（桌面端）
        videoPlayer.addEventListener('mousedown', (e) => {
            e.preventDefault();
            touchStartTime = Date.now();
            touchStartX = e.clientX;
            touchStartY = e.clientY;
            isLongPress = false;

            longPressTimer = setTimeout(() => {
                isLongPress = true;
                this.sendTouchEvent('longpress', touchStartX, touchStartY);
            }, 500);
        });

        videoPlayer.addEventListener('mouseup', (e) => {
            e.preventDefault();
            if (longPressTimer) {
                clearTimeout(longPressTimer);
            }

            if (!isLongPress) {
                const touchEndTime = Date.now();
                const duration = touchEndTime - touchStartTime;

                if (duration < 200) {
                    this.sendTouchEvent('tap', e.clientX, e.clientY);
                } else {
                    const deltaX = e.clientX - touchStartX;
                    const deltaY = e.clientY - touchStartY;
                    
                    if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
                        this.sendTouchEvent('swipe', {
                            startX: touchStartX,
                            startY: touchStartY,
                            endX: e.clientX,
                            endY: e.clientY
                        }, duration);
                    }
                }
            }
        });
    }

    async checkServerStatus() {
        try {
            const response = await fetch('/api/devices');
            if (response.ok) {
                this.updateStatus('server', 'connected');
                this.updateStatus('adb', 'connected');
            } else {
                this.updateStatus('server', 'error');
                this.updateStatus('adb', 'error');
            }
        } catch (error) {
            console.error('检查服务器状态失败:', error);
            this.updateStatus('server', 'error');
            this.updateStatus('adb', 'error');
        }
    }

    updateStatus(type, status) {
        const statusElement = document.getElementById(`${type}Status`);
        if (!statusElement) return;

        let text = '';
        let icon = '';

        switch (type) {
            case 'server':
                switch (status) {
                    case 'connected':
                        text = '服务器状态: 已连接';
                        icon = 'fas fa-check-circle';
                        break;
                    case 'disconnected':
                        text = '服务器状态: 已断开';
                        icon = 'fas fa-times-circle';
                        break;
                    case 'error':
                        text = '服务器状态: 连接失败';
                        icon = 'fas fa-exclamation-triangle';
                        break;
                    default:
                        text = '服务器状态: 检查中...';
                        icon = 'fas fa-spinner fa-spin';
                }
                break;
            case 'scrcpy':
                switch (status) {
                    case 'installed':
                        text = 'scrcpy: 已安装';
                        icon = 'fas fa-check-circle';
                        break;
                    case 'not_installed':
                        text = 'scrcpy: 未安装';
                        icon = 'fas fa-times-circle';
                        break;
                    default:
                        text = 'scrcpy: 检查中...';
                        icon = 'fas fa-spinner fa-spin';
                }
                break;
            case 'adb':
                switch (status) {
                    case 'connected':
                        text = 'ADB: 已连接';
                        icon = 'fas fa-check-circle';
                        break;
                    case 'error':
                        text = 'ADB: 连接失败';
                        icon = 'fas fa-exclamation-triangle';
                        break;
                    default:
                        text = 'ADB: 检查中...';
                        icon = 'fas fa-spinner fa-spin';
                }
                break;
        }

        statusElement.innerHTML = `<i class="${icon}"></i><span>${text}</span>`;
    }

    async loadDevices() {
        const deviceList = document.getElementById('deviceList');
        const noDevices = document.getElementById('noDevices');

        try {
            deviceList.innerHTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i><span>正在扫描设备...</span></div>';
            
            const response = await fetch('/api/devices');
            const data = await response.json();

            if (response.ok && data.devices && data.devices.length > 0) {
                this.renderDeviceList(data.devices);
                noDevices.style.display = 'none';
            } else {
                deviceList.innerHTML = '';
                noDevices.style.display = 'block';
            }
        } catch (error) {
            console.error('加载设备列表失败:', error);
            deviceList.innerHTML = '';
            noDevices.style.display = 'block';
            this.showNotification('加载设备列表失败', 'error');
        }
    }

    renderDeviceList(devices) {
        const deviceList = document.getElementById('deviceList');
        
        deviceList.innerHTML = devices.map(device => `
            <div class="device-card ${device.isStreaming ? 'streaming' : ''}" data-device-id="${device.id}">
                <div class="device-info">
                    <div class="device-id">${device.id}</div>
                    <div class="device-status">
                        <span class="status-badge ${device.status === 'device' ? 'connected' : ''}">
                            ${device.status === 'device' ? '已连接' : device.status}
                        </span>
                        ${device.isStreaming ? '<span class="status-badge streaming">投屏中</span>' : ''}
                    </div>
                </div>
                <div class="device-actions">
                    ${device.isStreaming ? 
                        `<button class="btn btn-danger" onclick="app.stopStreaming()">
                            <i class="fas fa-stop"></i> 停止投屏
                        </button>` :
                        `<button class="btn btn-primary" onclick="app.startStreaming('${device.id}')">
                            <i class="fas fa-play"></i> 开始投屏
                        </button>`
                    }
                    <button class="btn btn-info" onclick="app.showDeviceInfo('${device.id}')">
                        <i class="fas fa-info-circle"></i> 设备信息
                    </button>
                </div>
            </div>
        `).join('');
    }

    async startStreaming(deviceId) {
        if (!deviceId) {
            deviceId = this.currentDevice;
        }

        if (!deviceId) {
            this.showNotification('请先选择设备', 'warning');
            return;
        }

        try {
            this.showNotification('正在启动投屏...', 'info');
            
            const response = await fetch('/api/start-stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ deviceId })
            });

            const data = await response.json();

            if (response.ok && data.success) {
                this.currentDevice = deviceId;
                this.isStreaming = true;
                this.showStreamingPage();
                this.loadDeviceInfo(deviceId);
                
                // 设置视频流处理
                this.setupVideoStream(deviceId);
                
                this.showNotification('投屏已启动，正在接收视频流...', 'success');
            } else {
                throw new Error(data.error || '启动投屏失败');
            }
        } catch (error) {
            console.error('启动投屏失败:', error);
            this.showNotification(error.message, 'error');
        }
    }



    // 设置视频流处理
    setupVideoStream(deviceId) {
        // 发送设备连接事件
        this.socket.emit('device:connect', deviceId);

        // 监听H.264视频流数据
        this.socket.on(`stream:${deviceId}`, (data) => {
            console.log('收到H.264视频流数据:', data.byteLength, '字节');
            this.handleH264Stream(data);
        });

        // 监听错误信息
        this.socket.on(`error:${deviceId}`, (message) => {
            console.error('投屏错误:', message);
            this.showNotification(`投屏错误: ${message}`, 'error');
        });

        // 监听断开连接
        this.socket.on(`disconnect:${deviceId}`, (message) => {
            console.log('设备断开连接:', deviceId);
            this.isStreaming = false;
            this.showNotification('设备已断开连接', 'warning');
            this.showDeviceList();
        });

        // 监听信息消息
        this.socket.on(`info:${deviceId}`, (message) => {
            console.log('scrcpy信息:', message);
        });

        // 初始化H.264播放器
        this.initializeH264Player();
        
        console.log('H.264视频流处理已设置:', deviceId);
    }

    // 处理H.264视频流
    handleH264Stream(data) {
        if (!data || data.byteLength === 0) return;
        
        console.log('处理H.264数据:', data.byteLength, '字节');
        
        // 使用Canvas显示数据可视化
        this.displayVideoOnCanvas(data);
        
        // 检查是否为H.264 NAL单元
        const view = new Uint8Array(data);
        let nalCount = 0;
        
        // 查找H.264 NAL单元起始码
        for (let i = 0; i < view.length - 3; i++) {
            if (view[i] === 0x00 && view[i + 1] === 0x00 && 
                view[i + 2] === 0x00 && view[i + 3] === 0x01) {
                nalCount++;
            }
        }
        
        console.log('H.264 NAL单元数:', nalCount);
        
        // 如果检测到H.264数据且播放器未初始化，则初始化播放器
        if (nalCount > 0 && !this.h264Player) {
            console.log('检测到H.264数据，开始初始化播放器');
            this.initializeH264Player();
        }
        
        // 如果播放器已准备就绪，处理数据
        if (this.h264Player && this.h264Player.readyState === 4) {
            try {
                this.h264Player.appendBuffer(data);
                console.log('H.264数据已添加到播放器');
            } catch (error) {
                console.error('添加H.264数据失败:', error);
            }
        } else {
            // 如果播放器未准备就绪，将数据加入队列
            if (!this.h264Queue) this.h264Queue = [];
            this.h264Queue.push(data);
            console.log('H.264数据已加入队列，当前长度:', this.h264Queue.length);
        }
    }

    // 初始化MP4播放器
    initializeMP4Player() {
        try {
            // 创建MediaSource
            this.mediaSource = new MediaSource();
            const videoPlayer = document.getElementById('videoPlayer');
            videoPlayer.src = URL.createObjectURL(this.mediaSource);
            videoPlayer.style.display = 'block'; // 显示video元素
            
            // 隐藏Canvas
            if (this.canvas) {
                this.canvas.style.display = 'none';
            }

            this.mediaSource.addEventListener('sourceopen', () => {
                console.log('MediaSource已打开，创建MP4 SourceBuffer');
                
                try {
                    // 创建MP4 SourceBuffer
                    this.mp4Player = this.mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E"');
                    
                    this.mp4Player.addEventListener('updateend', () => {
                        // 处理队列中的数据
                        if (this.mp4Queue && this.mp4Queue.length > 0) {
                            const data = this.mp4Queue.shift();
                            try {
                                this.mp4Player.appendBuffer(data);
                            } catch (error) {
                                console.error('处理队列中的MP4数据失败:', error);
                            }
                        }
                    });

                    this.mp4Player.addEventListener('error', (error) => {
                        console.error('MP4 SourceBuffer错误:', error);
                    });
                    
                    console.log('MP4播放器初始化成功');
                    
                } catch (error) {
                    console.error('创建MP4 SourceBuffer失败:', error);
                    this.showNotification('MP4播放器初始化失败', 'error');
                }
            });

            this.mediaSource.addEventListener('error', (error) => {
                console.error('MediaSource错误:', error);
            });

            console.log('MP4播放器初始化完成');
            
        } catch (error) {
            console.error('初始化MP4播放器失败:', error);
            this.showNotification('视频播放器初始化失败', 'error');
        }
    }



    setupVideoStream(deviceId) {
        // 设置Socket.io事件监听
        this.socket.emit('device:connect', deviceId);

        // 监听MP4视频流数据
        this.socket.on(`stream:${deviceId}`, (data) => {
            console.log('收到MP4视频流数据:', data.byteLength, '字节');
            this.handleMP4Stream(data);
        });

        // 监听错误信息
        this.socket.on(`error:${deviceId}`, (message) => {
            console.error('投屏错误:', message);
            this.showNotification(`投屏错误: ${message}`, 'error');
        });

        // 监听断开连接
        this.socket.on(`disconnect:${deviceId}`, () => {
            console.log('设备断开连接:', deviceId);
            this.isStreaming = false;
            this.showNotification('设备已断开连接', 'warning');
            this.showDeviceList();
        });

        // 监听信息消息
        this.socket.on(`info:${deviceId}`, (message) => {
            console.log('scrcpy信息:', message);
        });

        // 更新Canvas显示状态
        this.updateCanvasStatus('正在接收视频流...', '请稍候...');
    }



    initializeMediaSource() {
        try {
            this.mediaSource = new MediaSource();
            const videoPlayer = document.getElementById('videoPlayer');
            videoPlayer.src = URL.createObjectURL(this.mediaSource);

            this.mediaSource.addEventListener('sourceopen', () => {
                // 对于MP4流，我们需要等待完整的文件头
                console.log('MediaSource已打开，等待MP4文件头...');
                
                // 创建SourceBuffer，使用MP4的MIME类型
                try {
                    this.sourceBuffer = this.mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E"');
                    console.log('成功创建MP4 SourceBuffer');
                    
                    this.sourceBuffer.addEventListener('updateend', () => {
                        if (this.videoQueue.length > 0) {
                            const data = this.videoQueue.shift();
                            try {
                                this.sourceBuffer.appendBuffer(data);
                            } catch (error) {
                                console.error('处理队列中的MP4数据失败:', error);
                            }
                        }
                    });

                    this.sourceBuffer.addEventListener('error', (error) => {
                        console.error('SourceBuffer错误:', error);
                    });
                    
                    this.sourceBuffer.addEventListener('abort', (error) => {
                        console.error('SourceBuffer中止:', error);
                    });
                    
                } catch (error) {
                    console.error('创建MP4 SourceBuffer失败:', error);
                    // 尝试其他编解码器
                    this.tryAlternativeCodecs();
                }
            });

            this.mediaSource.addEventListener('error', (error) => {
                console.error('MediaSource错误:', error);
            });

        } catch (error) {
            console.error('初始化MediaSource失败:', error);
        }
    }

    // 尝试其他编解码器
    tryAlternativeCodecs() {
        const codecs = [
            'video/mp4; codecs="avc1.640028"',
            'video/mp4; codecs="avc1.4D401E"',
            'video/mp4; codecs="avc1.42E01F"'
        ];
        
        let codecIndex = 0;
        const tryCodec = () => {
            if (codecIndex >= codecs.length) {
                console.error('所有MP4编解码器都失败');
                return;
            }
            
            try {
                this.sourceBuffer = this.mediaSource.addSourceBuffer(codecs[codecIndex]);
                console.log('成功使用MP4编解码器:', codecs[codecIndex]);
                
                this.sourceBuffer.addEventListener('updateend', () => {
                    if (this.videoQueue.length > 0) {
                        const data = this.videoQueue.shift();
                        try {
                            this.sourceBuffer.appendBuffer(data);
                        } catch (error) {
                            console.error('处理队列中的MP4数据失败:', error);
                        }
                    }
                });

                this.sourceBuffer.addEventListener('error', (error) => {
                    console.error('SourceBuffer错误:', error);
                });
                
                this.sourceBuffer.addEventListener('abort', (error) => {
                    console.error('SourceBuffer中止:', error);
                });
                
            } catch (error) {
                console.log('MP4编解码器失败:', codecs[codecIndex], error.message);
                codecIndex++;
                tryCodec();
            }
        };
        
        tryCodec();
    }

    // 创建简单的视频显示方法
    createSimpleVideoDisplay() {
        const videoPlayer = document.getElementById('videoPlayer');
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸 - 调整为更小的尺寸
        canvas.width = 480;
        canvas.height = 854;
        canvas.style.width = '100%';
        canvas.style.height = 'auto';
        canvas.style.maxWidth = '600px'; // 限制最大宽度
        canvas.style.maxHeight = '800px'; // 限制最大高度
        
        // 将Canvas插入到video元素后面，而不是替换它
        videoPlayer.parentNode.insertBefore(canvas, videoPlayer.nextSibling);
        
        // 隐藏video元素，但保留它用于MediaSource
        videoPlayer.style.display = 'none';
        
        // 绘制占位符
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#fff';
        ctx.font = '20px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('正在接收视频流...', canvas.width / 2, canvas.height / 2);
        ctx.font = '16px Arial';
        ctx.fillText('设备: ' + this.currentDevice, canvas.width / 2, canvas.height / 2 + 30);
        
        this.canvas = canvas;
        this.ctx = ctx;
        
        console.log('已创建Canvas视频显示，尺寸:', canvas.width, 'x', canvas.height);
    }

    // 在Canvas上显示视频数据
    displayVideoOnCanvas(data) {
        if (!this.canvas || !this.ctx) return;
        
        try {
            const ctx = this.ctx;
            const canvas = this.canvas;
            
            // 更新Canvas状态显示
            this.updateCanvasStatus('正在处理视频流...', `数据大小: ${data.byteLength} 字节`);
            
            // 尝试解析MP4数据
            const view = new Uint8Array(data);
            
            // 清空画布
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 检查是否为MP4文件头
            let isMP4Header = false;
            if (view.length >= 8) {
                isMP4Header = view[4] === 0x66 && view[5] === 0x74 && 
                              view[6] === 0x79 && view[7] === 0x70; // 'ftyp'
            }
            
            // 绘制数据可视化
            ctx.fillStyle = '#0f0';
            const barWidth = canvas.width / 100;
            const maxHeight = canvas.height - 150;
            
            for (let i = 0; i < Math.min(100, view.length); i++) {
                const height = (view[i] / 255) * maxHeight;
                const x = i * barWidth;
                const y = canvas.height - height - 100;
                
                ctx.fillRect(x, y, barWidth - 1, height);
            }
            
            // 显示状态信息
            ctx.fillStyle = '#fff';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(`MP4视频流数据: ${data.byteLength} 字节`, canvas.width / 2, 30);
            ctx.fillText(`MP4缓冲区: ${this.mp4Buffer ? this.mp4Buffer.length : 0} 字节`, canvas.width / 2, 50);
            ctx.fillText(`MP4文件头: ${isMP4Header ? '是' : '否'}`, canvas.width / 2, 70);
            ctx.fillText(`设备: ${this.currentDevice}`, canvas.width / 2, 90);
            ctx.fillText('正在累积MP4数据...', canvas.width / 2, canvas.height - 20);
            
            console.log('Canvas已更新，显示MP4数据可视化，缓冲区大小:', this.mp4Buffer ? this.mp4Buffer.length : 0);
            
        } catch (error) {
            console.error('Canvas显示视频数据失败:', error);
            this.updateCanvasStatus('视频显示错误', error.message);
        }
    }

    // 更新Canvas显示状态
    updateCanvasStatus(message, subMessage = '') {
        if (this.canvas && this.ctx) {
            const ctx = this.ctx;
            const canvas = this.canvas;
            
            // 清空画布
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制主消息
            ctx.fillStyle = '#fff';
            ctx.font = '20px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(message, canvas.width / 2, canvas.height / 2);
            
            // 绘制子消息
            if (subMessage) {
                ctx.font = '16px Arial';
                ctx.fillText(subMessage, canvas.width / 2, canvas.height / 2 + 30);
            }
            
            // 绘制设备ID
            ctx.font = '16px Arial';
            ctx.fillText('设备: ' + this.currentDevice, canvas.width / 2, canvas.height / 2 + 60);
            
            console.log('Canvas状态已更新:', message);
        }
    }

    cleanupSourceBuffer() {
        if (this.sourceBuffer && this.sourceBuffer.buffered.length > 0) {
            try {
                const start = this.sourceBuffer.buffered.start(0);
                const end = this.sourceBuffer.buffered.end(0);
                const duration = end - start;
                
                // 如果缓冲区超过10秒，清理前面的数据
                if (duration > 10) {
                    this.sourceBuffer.remove(start, start + 5);
                    console.log('已清理缓冲区前面的5秒数据');
                }
            } catch (error) {
                console.error('清理缓冲区失败:', error);
            }
        }
    }

    async stopStreaming() {
        if (!this.currentDevice) {
            this.showNotification('没有正在运行的投屏', 'warning');
            return;
        }

        try {
            const response = await fetch('/api/stop-stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ deviceId: this.currentDevice })
            });

            const data = await response.json();

            if (response.ok && data.success) {
                this.isStreaming = false;
                this.currentDevice = null;
                this.showNotification('投屏已停止', 'success');
                this.showDeviceList();
            } else {
                throw new Error(data.error || '停止投屏失败');
            }
        } catch (error) {
            console.error('停止投屏失败:', error);
            this.showNotification(error.message, 'error');
        }
    }

    async loadDeviceInfo(deviceId) {
        try {
            const response = await fetch(`/api/device/${deviceId}/info`);
            const data = await response.json();

            if (response.ok) {
                this.renderDeviceInfo(data);
            } else {
                throw new Error(data.error || '获取设备信息失败');
            }
        } catch (error) {
            console.error('获取设备信息失败:', error);
            this.showNotification('获取设备信息失败', 'error');
        }
    }

    renderDeviceInfo(deviceInfo) {
        const content = document.getElementById('deviceInfoContent');
        
        content.innerHTML = `
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">制造商</div>
                    <div class="info-value">${deviceInfo.manufacturer}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">型号</div>
                    <div class="info-value">${deviceInfo.model}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Android版本</div>
                    <div class="info-value">${deviceInfo.androidVersion}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">SDK版本</div>
                    <div class="info-value">${deviceInfo.sdkVersion}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">屏幕密度</div>
                    <div class="info-value">${deviceInfo.resolution}</div>
                </div>
            </div>
        `;
    }

    toggleDeviceInfo() {
        const content = document.getElementById('deviceInfoContent');
        const toggleBtn = document.getElementById('toggleDeviceInfo');
        const icon = toggleBtn.querySelector('i');

        if (content.classList.contains('expanded')) {
            content.classList.remove('expanded');
            icon.className = 'fas fa-chevron-down';
        } else {
            content.classList.add('expanded');
            icon.className = 'fas fa-chevron-up';
        }
    }

    async takeScreenshot() {
        if (!this.currentDevice) {
            this.showNotification('请先选择设备', 'warning');
            return;
        }

        try {
            this.showNotification('正在截图...', 'info');
            
            const response = await fetch('/api/screenshot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ deviceId: this.currentDevice })
            });

            const data = await response.json();

            if (response.ok && data.success) {
                // 创建下载链接
                const link = document.createElement('a');
                link.href = data.url;
                link.download = data.filename;
                link.click();
                
                this.showNotification('截图已保存', 'success');
            } else {
                throw new Error(data.error || '截图失败');
            }
        } catch (error) {
            console.error('截图失败:', error);
            this.showNotification(error.message, 'error');
        }
    }

    handleControlAction(action) {
        if (!this.currentDevice) {
            this.showNotification('请先选择设备', 'warning');
            return;
        }

        let keyCode = '';
        switch (action) {
            case 'home':
                keyCode = 'KEYCODE_HOME';
                break;
            case 'back':
                keyCode = 'KEYCODE_BACK';
                break;
            case 'app_switch':
                keyCode = 'KEYCODE_APP_SWITCH';
                break;
            case 'power':
                keyCode = 'KEYCODE_POWER';
                break;
            case 'volume_up':
                keyCode = 'KEYCODE_VOLUME_UP';
                break;
            case 'volume_down':
                keyCode = 'KEYCODE_VOLUME_DOWN';
                break;
            case 'volume_mute':
                keyCode = 'KEYCODE_VOLUME_MUTE';
                break;
            default:
                this.showNotification('未知的控制操作', 'warning');
                return;
        }

        this.sendTouchEvent('keyevent', null, null, keyCode);
    }

    sendText() {
        const textInput = document.getElementById('textInput');
        const text = textInput.value.trim();

        if (!text) {
            this.showNotification('请输入要发送的文本', 'warning');
            return;
        }

        if (!this.currentDevice) {
            this.showNotification('请先选择设备', 'warning');
            return;
        }

        this.sendTouchEvent('text', text);
        textInput.value = '';
        this.showNotification('文本已发送', 'success');
    }

    sendTouchEvent(type, x, y, action = null, duration = null) {
        if (!this.currentDevice) return;

        const data = {
            deviceId: this.currentDevice,
            type: type
        };

        switch (type) {
            case 'tap':
                data.x = x;
                data.y = y;
                break;
            case 'swipe':
                data.x = x;
                data.duration = duration;
                break;
            case 'keyevent':
                data.action = action;
                break;
            case 'text':
                data.x = x;
                break;
            case 'longpress':
                data.x = x;
                data.y = y;
                break;
        }

        this.socket.emit('user:input', data);
    }

    showStreamingPage() {
        document.getElementById('deviceListPage').classList.remove('active');
        document.getElementById('streamingPage').classList.add('active');
        
        document.getElementById('streamingDeviceName').textContent = `设备投屏 - ${this.currentDevice}`;
        
        // 隐藏视频覆盖层
        document.getElementById('videoOverlay').classList.add('hidden');
        
        // 显示触摸提示
        document.getElementById('touchHint').style.display = 'flex';
        
        // 创建Canvas视频显示
        this.createSimpleVideoDisplay();
        
        // 显示初始状态
        this.updateCanvasStatus('准备启动投屏...', '请稍候...');
    }

    showDeviceList() {
        document.getElementById('streamingPage').classList.remove('active');
        document.getElementById('deviceListPage').classList.add('active');
        
        // 重置视频播放器
        const videoPlayer = document.getElementById('videoPlayer');
        videoPlayer.src = '';
        videoPlayer.style.display = 'block'; // 重新显示video元素
        
        // 显示视频覆盖层
        document.getElementById('videoOverlay').classList.remove('hidden');
        
        // 隐藏触摸提示
        document.getElementById('touchHint').style.display = 'none';
        
        // 清理MediaSource
        if (this.mediaSource) {
            if (this.mediaSource.readyState === 'open') {
                this.mediaSource.endOfStream();
            }
            this.mediaSource = null;
            this.sourceBuffer = null;
        }
        
        this.videoQueue = [];
        this.isProcessing = false;
    }

    showNotification(message, type = 'info') {
        const notifications = document.getElementById('notifications');
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <span>${message}</span>
                <button class="notification-close" onclick="this.parentElement.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;

        notifications.appendChild(notification);

        // 自动移除通知
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 5000);
    }
}

// 初始化应用
const app = new ScrcpyClient();

// 全局错误处理
window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error);
    app.showNotification('发生未知错误', 'error');
});

window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
    app.showNotification('操作失败', 'error');
}); 